<!--
 * @Author: hpc(hepch)
 * @Date: 2021-05-20 16:13:04
 * @LastEditors: 予程_hepch
 * @LastEditTime: 2022-03-14 13:39:56
 * @Description:filecontent
 * @Copyright: 超图软件华中平台客户中心 (SuperMap Software Co., Ltd. -Central China Platform)
-->
<template>
  <div>
    <div class="card-isExpend" v-show="isExpendCard" @click="isExpend">
      展开结果面板
    </div>
    <a-card
      class="search-result-card"
      :title="titledate"
      size="small"
      v-show="visible"
    >
      <div slot="extra">
        <second-track-search
          @child-event="secondbuildata"
          :secondsearchInfo="secondsearchInfo"
          style="float: left"
          v-if="visible"
        />
        <a-form layout="inline" style="float: left">
          <a-form-item>
            <a-button size="small" @click="isExpend" type="link">
              <a-icon type="down"></a-icon
            ></a-button>
            <a-button size="small" @click="onClose" type="link">
              <a-icon type="close"></a-icon
            ></a-button>
          </a-form-item>
        </a-form>
      </div>

      <div class="container">
        <a-table
          :loading="tableloading"
          :columns="columns"
          :data-source="tabledata"
          size="small"
          bordered
          :pagination="{ pageSize: 6 }"
          :row-selection="{ onSelect: onSelect, onSelectAll: onSelectAll }"
        ></a-table>
      </div>
    </a-card>
  </div>
</template>

<script>
import L from "leaflet";

//import axios from 'axios'
import "leaflet.markercluster";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.animatedmarker/src/AnimatedMarker";
import "leaflet-polylinedecorator";
import { showBottomPanel, hideBottomPanel } from "@/utils/divResize";
import { wgs84togcj02 } from "@/utils/CoordinateTransform";
import SecondTrackSearch from "./SecondTrackSearch.vue";
//let mapv = require('mapv')
const columns = [
  {
    dataIndex: "gpsTime",
    key: "gpsTime",
    title: "记录时间",
  },

  {
    title: "经度",
    dataIndex: "lon",
    key: "lon",
  },
  {
    title: "纬度",
    dataIndex: "lat",
    key: "lat",
  },
  {
    dataIndex: "altitude",
    key: "altitude",
    title: "海拔",
  },
  {
    dataIndex: "direction",
    key: "direction",
    title: "方向",
  },
  {
    dataIndex: "vec1",
    key: "vec1",
    title: "速度（km/h）",
  },
];

export default {
  components: { SecondTrackSearch },
  mounted() {},
  data() {
    return {
      tableloading: false,
      columns,
      tabledata: [],
      visible: false,
      titledate: null,
      isExpendCard: false,
    };
  },
  watch: {
    visible: function () {
      console.log(this.visible);
    },
  },
  props: ["secondsearchInfo"],
  methods: {
    isExpend() {
      this.visible = !this.visible;
      this.isExpendCard = !this.isExpendCard;
      this.visible ? showBottomPanel() : hideBottomPanel();
    },
    secondbuildata(data) {
      this.tableloading = true;
      this.buildTableData(data);
      this.drawTrack(data);
    },

    removeMarker(markerid) {
      let markerlayer = this.locationLayer.getLayer(markerid);
      markerlayer.remove();
    },
    markerselectedLoation(record) {
      let location = wgs84togcj02(
        parseFloat(record.lon),
        parseFloat(record.lat)
      );
      let MarkerOptions = {
        icon: L.icon({
          iconSize: [35, 40],
          iconAnchor: [19, 13],
          iconUrl: "./img/icons/selectlocation.png",
        }),
      };

      let marker = L.marker(
        [parseFloat(location[1]), parseFloat(location[0])],
        MarkerOptions
      ); //.bindTooltip(`${item._source[selected_layer.esName]}`)
      let latlng = [location[1], location[0]];
      marker.on("click", () => {
        let content = `
	                       <div class="ant-table ant-table-scroll-position-left ant-table-small" style="max-height: 180px;overflow-y: scroll;">
	                                 <div class="ant-table-content"><!---->

	                                   <div class="ant-table-body">
	                                     <table class="">
	                                       <thead class="ant-table-thead">
	                                       <tr>
	                                         <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性名</span><span class="ant-table-column-sorter"></span></div></span></th>
	                                         <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性值</span><span class="ant-table-column-sorter"></span></div></span></th>
	                                       </tr>
	                                       </thead>
	                                       <tbody class="ant-table-tbody">`;
        for (let key in record) {
          let obj = this.columns.filter((item) => item.key === key)[0];
          if (obj) {
            content += `            <tr class="ant-table-row ant-table-row-level-0">
	                                             <td class="">${obj.title}</td>
	                                             <td class="">${record[key]}</td>
	                                           </tr>`;
          }
          //console.log(key, feature.properties[key]);
        }
        content += `
	                                       </tbody>
	                                     </table>
	                                   </div>
	                                 </div>
	                              </div>`;
        L.popup().setLatLng(latlng).setContent(content).openOn(this.map);
      });
      marker.addTo(this.locationLayer);
      record.markerid = this.locationLayer.getLayerId(marker);
      this.map.setView(latlng, 17);
    },
    onClose() {
      hideBottomPanel();
      this.tableloading = false;
      this.tabledata = [];
      this.visible = false;
    },
    onSelect(item, selected) {
      if (selected == false) {
        this.removeMarker(item.markerid);
      } else {
        this.markerselectedLoation(item);
      }
    },
    onSelectAll(selected, selectedRows) {
      this.locationLayer.clearLayers();
      if (selected == true) {
        selectedRows.map((item) => {
          this.markerselectedLoation(item);
        });
      }
    },
    buildTableData(array) {
      this.tabledata = [];
      let self = this;
      this.visible = true;
      array.map((item) => {
        let obj = {
          key: item.gpsTime,
          altitude: item.altitude,
          lon: item.lon,
          vec1: item.vec1,
          gpsTime: item.gpsTime,
          lat: item.lat,
          direction: item.direction,
        };
        self.tabledata.push(obj);
      });

      showBottomPanel();
      setTimeout(function () {
        self.titledate =
          self.secondsearchInfo.startDate.format("YYYY-MM-DD").toString() +
          "日车辆轨迹点数据:";
        self.tableloading = false;
      }, 500);
    },
    /**
     * @description:绘制轨迹车辆历史轨迹
     * @param {*} tollList
     * @return {*}
     */

    drawTrack(tollList) {
      this.vehicleTrackGroup.clearLayers();
      this.vehicleLocationGroup.clearLayers();
      this.locationLayer = new L.featureGroup().addTo(
        this.vehicleLocationGroup
      );

      // this.vehicleLocationGroup.clearLayers()
      let lineOptions = {
        weight: 8,
      };
      let latlngs = [];
      for (let i in tollList) {
        let latlng = wgs84togcj02(
          parseFloat(tollList[i].lon),
          parseFloat(tollList[i].lat)
        );
        latlngs.push([parseFloat(latlng[1]), parseFloat(latlng[0])]);
      }
      let routeLine = L.polyline(latlngs, lineOptions).addTo(
        this.vehicleTrackGroup
      );

      // 轨迹方向箭头
      L.polylineDecorator(routeLine, {
        patterns: [
          {
            repeat: 50,
            symbol: L.Symbol.arrowHead({
              pixelSize: 5,
              headAngle: 75,
              polygon: false,
              pathOptions: {
                stroke: true,
                weight: 2,
                color: "#FFFFFF",
              },
            }),
          },
        ],
      }).addTo(this.vehicleTrackGroup);
      let startIcon = L.icon({
        iconSize: [35, 40],
        iconAnchor: [19, 13],
        iconUrl: "./img/icons/startIcon.png",
      });
      let endIcon = L.icon({
        iconSize: [35, 40],
        iconAnchor: [19, 13],
        iconUrl: "./img/icons/endIcon.png",
      });
      L.marker(latlngs[0], { icon: startIcon }).addTo(this.vehicleTrackGroup);
      L.marker(latlngs[latlngs.length - 1], { icon: endIcon }).addTo(
        this.vehicleTrackGroup
      );
      this.map.flyToBounds(this.vehicleTrackGroup.getBounds());
      //setTimeout(this.animateMark(routeLine), 5000)
    },
    /**
     * @description: 添加动态marker
     * @param {*}
     * @return {*}
     */

    animateMark(routeLine) {
      //	let self = this
      let carIcon = L.icon({
        iconSize: [37, 26],
        iconAnchor: [19, 13],
        iconUrl: "./img/icons/vehicle.png",
      });
      // 动态marker

      this.animatemark = L.animatedMarker(routeLine.getLatLngs(), {
        interval: 500, // 默认为100mm
        icon: carIcon,
        autoStart: true,
        playCall: function (latlng, routeLine) {
          let realLineOptions = {
            weight: 8,
            color: "#FF9900",
          };
          console.log(latlng);
          let realRouteLine = L.polyline([], realLineOptions).addTo(
            this.vehicleTrackGroup
          );
          let newLatlngs = [routeLine.getLatLngs()[0]];
          newLatlngs.push(latlng);
          realRouteLine.setLatLngs(newLatlngs);
        },
      }).addTo(this.vehicleTrackGroup);
    },
    osearch(data) {
      console.log(data);
    },
    /**
     * @description: 动画结束后重新开启
     * @param {*} animatedmarker
     * @return {*}
     */

    startadimateMarker() {
      this.animatemark.start();
    },
    // /**
    //  * @description: 绘制行走的轨迹线
    //  * @param {*}
    //  * @return {*}
    //  */
    // updateRealLine(latlng) {
    // 	let realLineOptions = {
    // 		weight: 8,
    // 		color: '#FF9900',
    // 	}
    // 	console.log(latlng)
    // 	let realRouteLine = L.polyline([], realLineOptions).addTo(this.vehicleTrackGroup)
    // 	let newLatlngs = [routeLine.getLatLngs()[0]]
    // 	newLatlngs.push(latlng)
    // 	realRouteLine.setLatLngs(newLatlngs)
    // },
    markAtypeVehicles(locations, record) {
      this.vehicleLocationGroup.clearLayers();

      let geojsonMarkerOptions = {
        radius: 8,
        fillColor: "green",
        color: "#000",
        weight: 1,
        opacity: 1,
        fillOpacity: 1,
      };

      let nodelayer = new L.MarkerClusterGroup({
        spiderfyOnMaxZoom: false,
        showCoverageOnHover: true,
        zoomToBoundsOnClick: false,
        disableClusteringAtZoom: 17,
      });

      // let vehicleIcon = L.icon({
      // 	iconSize: [30, 40],
      // 	iconAnchor: [19, 13],
      // 	iconUrl: '../img/icons/vehicle.png',
      // })
      // var MarkerOptions = {
      // 	icon: vehicleIcon,
      // }
      console.log(record);
      for (let i in locations) {
        let item = locations[i];
        let marker = L.circleMarker(
          [item["GEO_LAT"], item["GEO_LNG"]],
          geojsonMarkerOptions
        );
        //.bindTooltip(`${item._source[selected_layer.esName]}`)
        let latlng = [item.GEO_LAT, item.GEO_LNG];

        marker.on("click", () => {
          let content = `
					        <div class="ant-table ant-table-scroll-position-left ant-table-small" style="max-height: 180px;overflow-y: scroll;">
					                     <div class="ant-table-content"><!---->

					                       <div class="ant-table-body">
					                         <table class="">
					                           <thead class="ant-table-thead">
					                           <tr>
					                             <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性名</span><span class="ant-table-column-sorter"></span></div></span></th>
					                             <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性值</span><span class="ant-table-column-sorter"></span></div></span></th>
					                           </tr>
					                           </thead>
					                           <tbody class="ant-table-tbody">`;
          for (let key in record) {
            //console.log(key, feature.properties[key]);

            content += `            <tr class="ant-table-row ant-table-row-level-0">
					                                 <td class="">${key}</td>
					                                 <td class="">${record[key]}</td>
					                               </tr>`;
          }
          content += `
					                           </tbody>
					                         </table>
					                       </div>
					                     </div>
					               </div>`;
          L.popup().setLatLng(latlng).setContent(content).openOn(this.map);
        });
        //marker.addTo(this.vehicleLocationGroup)

        nodelayer.addLayer(marker);
      }
      if (this.map.getZoom() > 8) {
        nodelayer.addTo(this.vehicleLocationGroup);
      }

      // this.map.flyToBounds(this.vehicleLocationGroup.getBounds())
    },

    /**
     * @description:标记选中车辆的当前位置
     * @param {*} location
     * @return {*}
     */

    markVehicle(location, record) {
      this.vehicleLocationGroup.clearLayers();
      location = wgs84togcj02(
        parseFloat(location["GEO_LNG"]),
        parseFloat(location["GEO_LAT"])
      );
      let MarkerOptions = {
        icon: L.icon({
          iconSize: [35, 40],
          iconAnchor: [19, 13],
          iconUrl: "./img/icons/location.png",
        }),
      };

      let marker = L.marker(
        [parseFloat(location[1]), parseFloat(location[0])],
        MarkerOptions
      ); //.bindTooltip(`${item._source[selected_layer.esName]}`)
      let latlng = [location[1], location[0]];
      marker.on("click", () => {
        let content = `
	                       <div class="ant-table ant-table-scroll-position-left ant-table-small" style="max-height: 180px;overflow-y: scroll;">
	                                 <div class="ant-table-content"><!---->

	                                   <div class="ant-table-body">
	                                     <table class="">
	                                       <thead class="ant-table-thead">
	                                       <tr>
	                                         <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性名</span><span class="ant-table-column-sorter"></span></div></span></th>
	                                         <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性值</span><span class="ant-table-column-sorter"></span></div></span></th>
	                                       </tr>
	                                       </thead>
	                                       <tbody class="ant-table-tbody">`;
        for (let key in record) {
          //console.log(key, feature.properties[key]);

          content += `            <tr class="ant-table-row ant-table-row-level-0">
	                                             <td class="">${key}</td>
	                                             <td class="">${record[key]}</td>
	                                           </tr>`;
        }
        content += `
	                                       </tbody>
	                                     </table>
	                                   </div>
	                                 </div>
	                              </div>`;
        L.popup().setLatLng(latlng).setContent(content).openOn(this.map);
      });
      marker.addTo(this.vehicleLocationGroup);
      this.map.flyToBounds(this.vehicleLocationGroup.getBounds());
    },
  },
  computed: {
    map() {
      return this.$store.state.map;
    },
    vehicleTrackGroup() {
      return this.$store.state.vehicleTrackGroup;
    },
    vehicleLocationGroup() {
      return this.$store.state.vehicleLocationGroup;
    },
  },
  created() {},
};
</script>

<style lang="less" scoped>
.card-isExpend {
  position: fixed;
  z-index: 999;
  left: 40%;
  bottom: 10px;
  width: 200px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  user-select: none;
  cursor: pointer;
  background-color: #fff;
  border-radius: 15px 15px 0 0;
  color: rgba(0, 0, 0, 0.85);
  border: 1px solid #d9d9d9;
}
.search-result-card {
  position: fixed;
  z-index: 99;
  right: 350px;
  left: 0;
  z-index: 999999;
  bottom: 0;
  .container {
    height: 320px;
    margin-top: 3px;
    overflow: scroll;
  }
}
/deep/.ant-card-extra {
  padding: 0 !important;
}
/deep/.ant-card-body {
  padding-top: 0 !important;
  padding-bottom: 0 !important;
}
/deep/.ant-tabs-bar {
  margin: 0 !important;
}
/deep/.ant-table-pagination.ant-pagination {
  margin: 5px 0 !important;
  float: right;
}
/deep/.ant-table-body {
  overflow-x: scroll;
}
/deep/.ant-card-small
  > .ant-card-head
  > .ant-card-head-wrapper
  > .ant-card-extra {
  padding: 0;
}
</style>
